﻿using System;
using GammaJul.ReSharper.GammaXaml.Psi;
using GammaJul.ReSharper.GammaXaml.Psi.Xaml;
using JetBrains.Annotations;
using JetBrains.Application.Progress;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Xaml.Bulbs;
using JetBrains.TextControl;

namespace GammaJul.ReSharper.GammaXaml.ContextActions.Xaml {

	/// <summary>
	/// Base class for context actions that remove a row or column definition.
	/// </summary>
	public class RemoveGridDefinitionItem : GridDefinitionItemBase {

		/// <summary>
		/// Gets the popup menu item text.
		/// </summary>
		public override string Text {
			get { return "Remove " + DefinitionType.ToString() + "Definition"; }
		}

		protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) {
			DefinitionInfo defInfo = GetDefinitionInfoAtCaret();
			if (defInfo == null)
				return null;

			int affectedIndex = defInfo.DefinitionsSetter.InnerTags.IndexOf(defInfo.Definition);

			// updates Grid.Row/Grid.Column and Grid.RowSpan/Grid.ColumnSpan on the children of the grid
			UpdateGridChildrenDefinitionValue(
				defInfo.Grid,
				defInfo.GridType,
				def => def >= affectedIndex ? def - 1 : def,
				(def, span) => def < affectedIndex && def + span - 1 >= affectedIndex ? span - 1 : span);
			defInfo.Definition.Delete();

			Provider.PsiServices.MarkAsDirty(Provider.SourceFile);
			return null;
		}

		public RemoveGridDefinitionItem([NotNull] XamlContextActionDataProvider provider, GridDefinitionType definitionType)
			: base(provider, definitionType) {
		}
	}

}